package org.jslaughter.component.aiming;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Input;
import org.nvframe.camera.Camera;
import org.nvframe.component.AbstractComponent;
import org.nvframe.component.state.Position;
import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.UpdateEvent;
import org.nvframe.event.eventtype.UpdateListener;
import org.nvframe.util.settings.SettingsObj;

/**
 * 
 * @author Nik Van Looy
 */
public class RotateToAim extends AbstractComponent implements UpdateListener {
	
	private float mouseTimer;
	
	public RotateToAim(String id, Entity owner, SettingsObj settings) {
		super(id, owner);

		mouseTimer = 0;
		
		EventService.getInstance().addEventListener(this);
	}

	public void onUpdate(UpdateEvent event) {
		GameContainer gc = event.getGc();
		int delta = event.getDelta();
		
		mouseTimer += delta;
		
		if (mouseTimer > 30) {
			Position position = (Position) owner.getComponent(Position.class);
			if(position == null)
				return;

			mouseTimer = 0;
			
			Input input = gc.getInput();

			int mouseX = Camera.getInstance().getMouseX(input);
			int mouseY = Camera.getInstance().getMouseY(input);
			
			float direction = (float) Math.toDegrees(Math.atan2(mouseY - position.getY(), 
					mouseX - position.getX()));

			position.setDirection(direction);
		} 
	}

}
